package cn.itcast.cloud.storage;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 大文件分片复制
 */
public class UploadPartCopySample {
    private static String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
    private static String accessKeyId = "LTAIXeZktAHXvAgc";
    private static String accessKeySecret = "iHpKZJ5KiB7imcohA7VgjDzLY2O87w";
    private static String bucketName = "jiaze";
    private static String key = "partcopy";

    private static OSSClient client = null;

    private static String sourceBucketName = "*** Provide source bucket name ***";
    private static String sourceKey = "*** Provide source key ***";
    private static String targetBucketName = "*** Provide target bucket name ***";
    private static String targetKey = "*** Provide target key ***";

    private static String localFilePath = "*** Provide local file path ***";

    @Test
    public void UploadPartCopy() throws Exception{
        client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(sourceBucketName, sourceKey, createSampleFile()));

        /*
         * Claim a new upload id for your target bucket
         */
        InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(targetBucketName, targetKey);
        InitiateMultipartUploadResult initiateMultipartUploadResult = client.initiateMultipartUpload(initiateMultipartUploadRequest);
        String uploadId = initiateMultipartUploadResult.getUploadId();

        /*
             * Calculate how many parts to be divided
             */
        final long partSize = 5 * 1024 * 1024L;   // 5MB
        ObjectMetadata metadata = client.getObjectMetadata(sourceBucketName, sourceKey);
        long objectSize = metadata.getContentLength();
        int partCount = (int) (objectSize / partSize);
        if (objectSize % partSize != 0) {
            partCount++;
        }
        if (partCount > 10000) {
            throw new RuntimeException("Total parts count should not exceed 10000");
        } else {
            System.out.println("Total parts count " + partCount + "\n");
        }

/*
             * Upload multiparts by copy mode
             */
        System.out.println("Begin to upload multiparts by copy mode to OSS\n");
        List<PartETag> partETags = new ArrayList<PartETag>();
        for (int i = 0; i < partCount; i++) {
            long startPos = i * partSize;
            long curPartSize = (i + 1 == partCount) ? (objectSize - startPos) : partSize;;

            UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(
                    sourceBucketName, sourceKey, targetBucketName, targetKey);
            uploadPartCopyRequest.setUploadId(uploadId);
            uploadPartCopyRequest.setPartSize(curPartSize);
            uploadPartCopyRequest.setBeginIndex(startPos);
            uploadPartCopyRequest.setPartNumber(i + 1);

            UploadPartCopyResult uploadPartCopyResult = client.uploadPartCopy(uploadPartCopyRequest);
            System.out.println("\tPart#" + uploadPartCopyResult.getPartNumber() + " done\n");
            partETags.add(uploadPartCopyResult.getPartETag());
        }

        /*
         * Complete to upload multiparts
         */
        System.out.println("Completing to upload multiparts\n");
        CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
                targetBucketName, targetKey, uploadId, partETags);
        client.completeMultipartUpload(completeMultipartUploadRequest);

        /*
         * Fetch the object that newly created at the step below.
         */
        System.out.println("Fetching an object");
        client.getObject(new GetObjectRequest(targetBucketName, targetKey), new File(localFilePath));
        client.shutdown();
    }

    private File createSampleFile() throws IOException {
        File file = File.createTempFile("oss-java-sdk-", ".txt");
        file.deleteOnExit();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        for (int i = 0; i < 1000000; i++) {
            writer.write("abcdefghijklmnopqrstuvwxyz\n");
            writer.write("0123456789011234567890\n");
        }
        writer.close();

        return file;
    }
}
